package com.atguigu.tingshu.order.interceptor.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.order.interceptor.OrderHandlerInterceptor;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class OrderRepeatSbumitValidOrderHandlerInterceptor implements OrderHandlerInterceptor {
   @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public OrderInfoVo sbumitOrderRequestProcess(OrderInfoVo orderInfoVo) {
        /**
         * 通过lua脚本保证判断redis中有无tradeNo和删除tradeNo的原子性，避免订单重复提交
         */
        String script = "if redis.call(\"exists\",KEYS[1])\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), List.of(RedisConstant.ORDER_TRADE_NO_PREFIX + orderInfoVo.getTradeNo()));
        if (result.intValue()==0){ //重复提交校验
            throw new GuiguException(ResultCodeEnum.REPEAT_SUBMIT);
        }
        log.info("{}订单重复校验通过了。。。。。", JSON.toJSONString(orderInfoVo));
        return orderInfoVo;
    }

    @Override
    public int sort() {
        return 2;
    }
}
